#coding=utf-8
import os, sys, datetime, time
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
import tsina
os.environ['DJANGO_SETTINGS_MODULE'] = 'gfw.settings'
from tsina.dbserver.models import Message, User

anti_keywords = ['@',]
reply = 'Hello, 想要流畅看youtube，发twitter看空姐，上facebook关注姚明。Try this http://item.taobao.com/auction/item_detail-0db1-91d8a9043743fe0a826498b87e43fb76.htm'

from optparse import OptionParser
parser = OptionParser()
parser.add_option('-u', '--user', dest='user', help=u'用户名')
parser.add_option('-p', '--password', dest='password', help=u'密码')
parser.add_option('-k', '--keyword', dest='keyword',help=u'关键词')
(options, args) = parser.parse_args()   

user = options.user
password = options.password
keyword = options.keyword

log = open(os.path.join(PROJECT_ROOT, 'log/add_comments.log'), 'a')

no_sent_time = datetime.datetime(1,1,1)

if m.user.is_sended:
  m.sent_at = no_sent_time
  m.save()
  sys.exit()

#判断微博内容有没有包括 anti_keyword
contain_anti_keyword = False
while True:
  m = Message.objects.filter(keyword=keyword).filter(sent_at=None).order_by('-published_at')[0]
  print m.content.encode('u8')

  for k in anti_keywords:
    if m.content.find(k) != -1:
      m.sent_at = no_sent_time
      m.save()
    
      log.write('Message:%s\n 有 antiword:%s\n'%(m.content.encode('u8'), k.encode('u8')))
      log.close()    
      
      contain_anti_keyword = True
      break
    contain_anti_keyword = False
    
  if not contain_anti_keyword:break 
  
t = tsina.TsinaRobot(user=user, password=password)
t.login()

code, r,c = t.add_comment(m, reply%m.user.user_id.encode('u8'))
if c == '{"code":"A00006"}':
  m.user.is_sended = True
  m.sent_at = datetime.datetime.now()
  m.save()
  m.user.save()
  log.close()
  
else:
  m.sent_at = no_sent_time
  m.save()
  log.write('发生错误 at %s\n'%datetime.datetime.now())
  log.write('返回值：%s\n'%c)
  log.write('Message是：%s\n'%m.content.encode('u8'))
  log.close()
